/*You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
*/


#include <iostream>
#include <map>
#include <string>
#include <deque>
#include <stack>
#include <vector>

//
struct ListNode
{
    int val;
    ListNode * next;
    ListNode(int x)
        :val(x), next(nullptr)
    {}
};

ListNode * addTwoNumbers (ListNode * L1, ListNode * L2)
{
    if (L1 == nullptr && L2 == nullptr) {
        return nullptr;
    }
    std::vector<int> first, second;
    ListNode * tmp = L1;
    while (tmp != nullptr) {
        first.emplace_back(tmp->val);
        tmp = tmp ->next;
    }
    tmp = L2;
    while (tmp != nullptr) {
        second.emplace_back(tmp->val);
        tmp = tmp ->next;
    }
    
    tmp = nullptr;
    ListNode * rst = new ListNode(0), * curr = nullptr;
    int i = 0, j = 0, carry = 0;
    curr = rst;
    while (i < first.size() && j < second.size()) {
        int element = first[i] + second[j] + carry;
        carry = element / 10;
        tmp = new ListNode(element % 10);
        curr->next = tmp;
        curr = curr->next;
        ++i;
        ++j;
    }
    while (i < first.size()) {
        int element = (first[i] + carry);
        tmp = new ListNode(element % 10);
        curr->next = tmp;
        curr = curr->next;
        carry = element / 10;
        ++i;
    }
    while (j < second.size()) {
        int element = (second[j] + carry);
        tmp = new ListNode(element % 10);
        curr->next = tmp;
        curr = curr->next;
        carry = element / 10;
        ++j;
    }
    if (carry == 1) {
        tmp = new ListNode(carry);
        curr->next = tmp;
    }
    return rst->next;
}

int main(int argc, const char * argv[])
{
    ListNode * root1 = new ListNode(1),
             * node1 = new ListNode(8),
             * node2 = new ListNode(3),
    * root2 = new ListNode(0),
             * node3 = new ListNode(6),
             * node4 = new ListNode(4);
    root1->next = node1;
    node1->next = node2;
    root2->next = node3;
    node3->next = node4;
    addTwoNumbers(root1, root2);
    return 0;
}
